package com.xuzz.study.security;

import sun.misc.BASE64Encoder;

import java.security.MessageDigest;

public class SHAUtil {

    public static void main(String[] args) throws Exception
    {
        String str = new String("xzz123");
        System.out.println("原始：" + str);
        System.out.println("SHA-Hex后：" + shaEncodeAsHex(str));

        System.out.println("SHA-BASE64 后：" + shaEncodeAsBase64(str));
    }

    public static String shaEncodeAsHex(String inStr) throws Exception {
        MessageDigest md = null;
        try
        {
            md = MessageDigest.getInstance("SHA");
        }
        catch (Exception ex)
        {

        }
        byte[] bytes = inStr.getBytes();
        byte[] md5Bytes = md.digest(bytes);

        StringBuffer hexValue = new StringBuffer();

        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }

        return hexValue.toString();
    }

    public static String shaEncodeAsBase64(String inStr) throws Exception {
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA");
        } catch (Exception ex) {

        }

        byte[] bytes = inStr.getBytes();
        byte[] md5Bytes = md.digest(bytes);

        BASE64Encoder base64en = new BASE64Encoder();
        return base64en.encode(md5Bytes);
    }
}
